package com.d2.modules.system.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.d2.modules.system.permission.entity.Role;
import com.d2.modules.system.permission.entity.User;
import com.d2.modules.system.permission.entity.vo.LoginUser;
import com.d2.modules.system.permission.mapper.IRoleMapper;
import com.d2.modules.system.permission.mapper.IUserMapper;
import com.d2.modules.system.permission.service.IRoleResourceService;
import com.d2.modules.system.permission.service.IRoleService;
import com.d2.modules.system.permission.service.IUserService;
import com.d2.modules.system.permission.util.filter.DataScope;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<IUserMapper, User> implements IUserService, UserDetailsService {
    @Autowired
    private IRoleResourceService roleResourceService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User query = new User();
        query.setUsername(s);
        User user = this.getOne(new QueryWrapper<>(query));
        List<String> permissions = roleResourceService.queryPermissionByUserId(user.getId());
        Set<GrantedAuthority> authorities = new HashSet<>();

        for (String p : permissions) {
            authorities.add(new SimpleGrantedAuthority(p));
        }

        List<Role> roles = roleMapper.queryRoleByUserId(user.getId());

        for (Role r : roles) {
            authorities.add(new SimpleGrantedAuthority("role:"+ r.getCode()));
        }

        log.info("流程权限列表：" + authorities);

        log.info("权限列表：{}", authorities);
        return new LoginUser(user, authorities);
    }

    @Override
    public User getUserByUsername(String s) {
        User user1 = new User();
        user1.setUsername(s);
        return this.getOne(new QueryWrapper<>(user1));
    }
}
